﻿using AutoMapper;
using ERPSystem.Common.Domains.PurchaseInvoiceCommon;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;
using SqlSugar;

namespace SalesManagementWrite.API.SalesManagementWrites.PurchaseInvoicees
{
    public class PurchaseInvoiceUpdateHandler : IRequestHandler<PurchaseInvoiceUpdateCommand, Result>
    {
        private readonly IBaseRepository<PurchaseInvoice> _purchaseInvoiceRepository;
        private readonly IBaseRepository<PurchaseInvoiceSubtable> _purchaseInvoiceSubtableRepository;
        private readonly IMapper _mapper;
        private readonly ISqlSugarClient _sqlSugarClient;

        public PurchaseInvoiceUpdateHandler(IBaseRepository<PurchaseInvoice> purchaseInvoiceRepository, IBaseRepository<PurchaseInvoiceSubtable> purchaseInvoiceSubtableRepository, IMapper mapper, ISqlSugarClient sqlSugarClient)
        {
            _purchaseInvoiceRepository = purchaseInvoiceRepository;
            _purchaseInvoiceSubtableRepository = purchaseInvoiceSubtableRepository;
            _mapper = mapper;
            _sqlSugarClient = sqlSugarClient;
        }
        /// <summary>
        /// 修改采购发票数据
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PurchaseInvoiceUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result();
            _sqlSugarClient.Ado.BeginTran();
            try
            {
                var purchaseInvoice = await(await _purchaseInvoiceRepository.GetAll()).FirstAsync(c => c.DocumentNo == request.DocumentNo);
                var purchaseInvoiceRes = await _purchaseInvoiceRepository.Update(purchaseInvoice);
                List<PurchaseInvoiceSubtable> purchaseInvoiceSubtable = new List<PurchaseInvoiceSubtable>();
                purchaseInvoiceSubtable = await(await _purchaseInvoiceSubtableRepository.GetAll()).Where(c => c.SerialNumber == request.SerialNumber).ToListAsync();
                var purchaseInvoiceSubtableRes = await _purchaseInvoiceSubtableRepository.UpdateRange(purchaseInvoiceSubtable);
                if (purchaseInvoiceRes > 0 && purchaseInvoiceSubtableRes > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "修改成功";
                }
                _sqlSugarClient.Ado.CommitTran();
                return result;
            }
            catch (Exception ex)
            {

                _sqlSugarClient.Ado.RollbackTran();
                throw ex;
            }
        }
    }
}
